#include "../util/TcpListener.h" 
#include "Dsm.h" 
 
#define BUFFER_SIZE 1024 
 
extern "C" { 
  #include <sys/time.h> 
} 
 
void usage() { 
  cout << "Usage: DsmTimeClient <name-server-port>" << endl; 
  exit(1); 
} 
 

// Evaluable 3.3.5. (6)

int main(int argc, char** argv) { 
	if (argc > 2) { 
		usage(); 
	} 
 
	PracticaCaso::DsmDriver * driver = new PracticaCaso::DsmDriver("127.0.0.1", atoi(argv[1]), "dsm.deusto.es");
	//PracticaCaso::DsmDriver * driver = new PracticaCaso::DsmDriver("127.0.0.1", 1234, "dsm.deusto.es");
	PracticaCaso::DsmData data; 
	cout << "Node created with NID: " << driver->get_nid() << endl;
	//creamos el loop infinito que va a estar solicitando esta variable cada segundo
	while (1) { 
	
	    // Esperamos hasta que la variable ha sido liberada
		
        bool timestampWait = false;
        while (!timestampWait) {
            try { 
				//usamos el metodo get para obtener la informacion de la variable
                data = driver->dsm_get("GLOBAL_TIMESTAMP");
                timestampWait = true;
            } catch (DsmException dsme) {
                cerr << "ERROR: dsm_get(\"GLOBAL_TIMESTAMP\") -  Waiting for other process to initialise it: " << dsme  << endl; 
                driver->dsm_wait("GLOBAL_TIMESTAMP"); 
            } 
        } 
        char* time; 
        time = ((char *)data.addr); 
        cout << time << endl; 
		//el segundo de espera hasta volver a solicitar la informacion
        sleep(1); 
    }
 
}
